import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadBaseApplication {
    private static final Object lock = new Object();
    private static boolean needWait = true;
    private static volatile boolean flag = false;
    private static int counter = 0;

    public static void main(String[] args) throws InterruptedException {
        // 1. 线程创建方式演示
        //threadCreationDemo();

        // 2. 线程状态演示
        //threadStateDemo();

        // 3. 线程同步机制演示
        //threadSynchronizationDemo();

        // 4. 线程安全问题演示
        threadSafetyDemo();
    }

    /**
     * 线程创建方式演示
     */
    private static void threadCreationDemo() throws InterruptedException {
        System.out.println("=== 线程创建方式演示 ===");

        // 方式1：继承Thread类
        Thread thread1 = new MyThread("Thread-1");
        thread1.start();

        // 方式2：实现Runnable接口
        Thread thread2 = new Thread(new MyRunnable(), "Thread-2");
        thread2.start();

        // 方式3：使用Lambda表达式
        Thread thread3 = new Thread(() -> {
            System.out.println("Lambda线程: " + Thread.currentThread().getName());
        }, "Thread-3");
        thread3.start();

        // 方式4：实现Callable接口（有返回值）
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new MyCallable());

        try {
            String result = future.get();  // 获取返回值
            System.out.println("Callable返回值: " + result);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        executor.shutdown();

        // 等待所有线程完成
        thread1.join();
        thread2.join();
        thread3.join();

        System.out.println();
    }

    /**
     * 线程状态演示
     */
    private static void threadStateDemo() throws InterruptedException {
        System.out.println("=== 线程状态演示 ===");

        Thread thread = new Thread(() -> {
            try {
                System.out.println("线程开始执行");

                // 模拟RUNNABLE状态
                Thread.sleep(1000);

                // 进入WAITING状态
                synchronized (lock) {
                    System.out.println("线程进入等待状态");
                    while (needWait) {
                        // 线程处于WAITING状态，等待被唤醒
                        lock.wait();
                    }
                    System.out.println("线程被唤醒");
                }

                System.out.println("线程执行完成");
            } catch (InterruptedException e) {
                System.out.println("线程被中断");
            }
        }, "StateDemo");

        System.out.println("创建后状态: " + thread.getState());  // NEW

        thread.start();
        System.out.println("启动后状态: " + thread.getState());  // RUNNABLE

        Thread.sleep(500);
        System.out.println("运行中状态: " + thread.getState());  // Thread.sleep(1000)导致TIMED_WAITING

        Thread.sleep(1000);
        System.out.println("等待中状态: " + thread.getState());  // WAITING

        // 唤醒线程
        synchronized (lock) {
            needWait = false;
            lock.notify();
        }

        thread.join();
        System.out.println("结束后状态: " + thread.getState());  // TERMINATED

        System.out.println();
    }

    /**
     * 线程同步机制演示
     */
    private static void threadSynchronizationDemo() throws InterruptedException {
        System.out.println("=== 线程同步机制演示 ===");

        // wait/notify演示
        Thread producer = new Thread(() -> {
            synchronized (lock) {
                System.out.println("生产者开始生产");
                flag = true;
                System.out.println("生产完成，通知消费者");
                lock.notify();  // 唤醒等待的消费者
            }
        }, "Producer");

        Thread consumer = new Thread(() -> {
            synchronized (lock) {
                while (!flag) {
                    try {
                        System.out.println("消费者等待产品");
                        lock.wait();  // 等待生产者通知
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                }
                System.out.println("消费者开始消费");
            }
        }, "Consumer");

        consumer.start();
        Thread.sleep(1000);  // 确保消费者先启动
        producer.start();

        producer.join();  // join不保证执行顺序，一般谁执行快，谁先join
        consumer.join();

        // 重置标志
        flag = false;

        System.out.println();
    }

    /**
     * 线程安全问题演示
     */
    private static void threadSafetyDemo() throws InterruptedException {
        System.out.println("=== 线程安全问题演示 ===");

        // 问题演示：多线程访问共享变量
        counter = 0;
        Thread[] threads = new Thread[10];

        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    counter++;  // 非原子操作，存在线程安全问题
                }
            });
            threads[i].start();
        }

        // 等待所有线程完成
        for (Thread thread : threads) {
            thread.join();
        }

        System.out.println("非线程安全结果: " + counter + " (期望: 10000)");

        // 解决方案1：使用synchronized
        counter = 0;
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    synchronized (ThreadBaseApplication.class) {
                        counter++;
                    }
                }
            });
            threads[i].start();
        }

        for (Thread thread : threads) {
            thread.join();
        }

        System.out.println("synchronized结果: " + counter + " (期望: 10000)");

        // 解决方案2：使用原子类
        AtomicInteger atomicCounter = new AtomicInteger(0);
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    atomicCounter.incrementAndGet();  // 原子操作
                }
            });
            threads[i].start();
        }

        for (Thread thread : threads) {
            thread.join();
        }

        System.out.println("AtomicInteger结果: " + atomicCounter.get() + " (期望: 10000)");

        System.out.println();
    }
}
/**
 * 继承Thread类的方式
 */
class MyThread extends Thread {
    public MyThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        System.out.println("MyThread运行: " + getName());
    }
}

/**
 * 实现Runnable接口的方式
 */
class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("MyRunnable运行: " + Thread.currentThread().getName());
    }
}

/**
 * 实现Callable接口的方式
 */
class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        Thread.sleep(1000);
        return "Callable执行完成: " + Thread.currentThread().getName();
    }
}